/*
 * ServerManagerPane.java
 *
 * Created on 16.3.2011, 15:46:02
 */
package cz.muni.fi.rum.gui.component;

import cz.muni.fi.rum.RumConfigurator;
import cz.muni.fi.rum.gui.FieldValidator;
import cz.muni.fi.rum.reflector.telnet.TelnetServerConections;
import cz.muni.fi.rum.reflector.telnet.TelnetServer;
import java.util.Arrays;
import javax.swing.AbstractListModel;
import org.jdesktop.application.Action;
import org.jdesktop.application.Task;

/**
 * Trida poskytujici gui komponentu pro spravu serveru.
 * Je pripojena na model z verze 1.0, konkretne na tridy z baliku {@link cz.muni.fi.rum.reflector.telnet}
 * Pro popis konkretniho chovani se podivejte do konkretnich trid modelu <code>TelnetServerConections</code>
 * a <code>TelnetServer</code>
 * 
 * @see TelnetServerConections
 * @see TelnetServer
 * @version 1.1
 * @since 21.3.2011
 * @author pmikulasek
 */
public class ServerManagerPane extends javax.swing.JPanel {

    private static ServerManagerPane instance;

    /** Creates new form ServerManagerPane */
    private ServerManagerPane() {
        initComponents();
    }

    /**
     * Metoda zabezpecuje navrhovy vzor singleton. Vraci instanci tridy {@link this}
     * @return this
     */
    public static ServerManagerPane getInstance() {
        if (instance == null) {
            instance = new ServerManagerPane();
        }
        return instance;
    }

    /**
     * Metoda vymaze obsah vsech textovych poli
     */
    private void resetAllFields() {
        addressField.setText("");
        portFormatedField.setText("");
        userNameField.setText("");
        passFieldOne.setText("");
        passFieldTwo.setText("");
    }

    /**
     * Akce ktera zpusobi nacteni informaci z poli,
     * jejich zkontrolovani a pokud je vsechno v poradku,
     * tak pridani serveru do seznamu ulozenych.
     * @return Vraci {@link ServerAddOrRemoveTask}
     */
    @Action
    public Task addServerToList() {
        feedBackLabel.setText("<html>");
        if (Arrays.equals(passFieldOne.getPassword(), passFieldTwo.getPassword())
                && !addressField.getText().isEmpty()
                && null != FieldValidator.getInstance().controlAndParsePortInteger(feedBackLabel, labelForPort.getText(), portFormatedField.getText(), true)) {

            TelnetServer ts = new TelnetServer(addressField.getText(),
                    Integer.valueOf(portFormatedField.getText()),
                    userNameField.getText(),
                    passFieldOne.getPassword());
            resetAllFields();
            return new ServerAddOrRemoveTask(ts, true);
        } else {
            return null;
        }

    }

    /**
     * Akce ktera zpusobi smazani oznaceneho serveru
     * @return Vraci {@link ServerAddOrRemoveTask}
     */
    @Action
    public Task deleteServerFromList() {
        Object obj = reflectorServerList.getSelectedValue();
        if (obj instanceof TelnetServer) {
            resetAllFields();
            return new ServerAddOrRemoveTask((TelnetServer) obj, false);
        } else {
            return null;
        }
    }

    /**
     * Privatni trida ktera zabezpecuje vykonani pozadavku pridani a odebrani serveru.
     */
    private class ServerAddOrRemoveTask extends Task<TelnetServer, Void> {

        private TelnetServerConections servers;
        private TelnetServer telnetServer;
        private boolean add;

        public ServerAddOrRemoveTask(TelnetServer telnetServer, boolean add) {
            super(RumConfigurator.getInstance());
            servers = TelnetServerConections.getInstance();
            this.telnetServer = telnetServer;
            this.add = add;
        }

        @Override
        protected TelnetServer doInBackground() throws Exception {
            if (add) {
                return servers.add(telnetServer);
            } else {
                return servers.delete(telnetServer);
            }
        }

        @Override
        protected void succeeded(TelnetServer result) {
            reflectorServerList.setModel(new AbstractListModel() {

                @Override
                public int getSize() {
                    return servers.getAllServers().size();
                }

                @Override
                public Object getElementAt(int index) {
                    return servers.getAllServers().get(index);
                }
            });
            reflectorServerList.validate();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        serverPane = new javax.swing.JPanel();
        updateServerListButton = new javax.swing.JButton();
        removeServerFromListButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        reflectorServerList = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        labelForServerName = new javax.swing.JLabel();
        addressField = new javax.swing.JTextField();
        labelForPort = new javax.swing.JLabel();
        portFormatedField = new javax.swing.JTextField();
        UserPane = new javax.swing.JPanel();
        loginLabel = new javax.swing.JLabel();
        userNameField = new javax.swing.JTextField();
        passwordLabel = new javax.swing.JLabel();
        repeatPasswordLabel = new javax.swing.JLabel();
        passFieldOne = new javax.swing.JPasswordField();
        passFieldTwo = new javax.swing.JPasswordField();
        feedBackLabel = new javax.swing.JLabel();

        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cz.muni.fi.rum.RumConfigurator.class).getContext().getResourceMap(ServerManagerPane.class);
        serverPane.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("serverPane.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 0, 11), resourceMap.getColor("serverPane.border.titleColor"))); // NOI18N
        serverPane.setName("serverPane"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(cz.muni.fi.rum.RumConfigurator.class).getContext().getActionMap(ServerManagerPane.class, this);
        updateServerListButton.setAction(actionMap.get("addServerToList")); // NOI18N
        updateServerListButton.setText(resourceMap.getString("updateServerListButton.text")); // NOI18N
        updateServerListButton.setName("updateServerListButton"); // NOI18N

        removeServerFromListButton.setAction(actionMap.get("deleteServerFromList")); // NOI18N
        removeServerFromListButton.setText(resourceMap.getString("removeServerFromListButton.text")); // NOI18N
        removeServerFromListButton.setName("removeServerFromListButton"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        reflectorServerList.setModel(new AbstractListModel() {

            @Override
            public int getSize() {
                return TelnetServerConections.getInstance().getAllServers().size();
            }

            @Override
            public Object getElementAt(int index) {
                return TelnetServerConections.getInstance().getAllServers().get(index);
            }
        });
        reflectorServerList.setName("reflectorServerList"); // NOI18N
        jScrollPane1.setViewportView(reflectorServerList);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), null)); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        labelForServerName.setText(resourceMap.getString("labelForServerName.text")); // NOI18N
        labelForServerName.setName("labelForServerName"); // NOI18N

        addressField.setToolTipText(resourceMap.getString("addressField.toolTipText")); // NOI18N
        addressField.setName("addressField"); // NOI18N

        labelForPort.setText(resourceMap.getString("labelForPort.text")); // NOI18N
        labelForPort.setName("labelForPort"); // NOI18N

        portFormatedField.setName("portFormatedField"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelForServerName)
                    .addComponent(addressField, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(labelForPort)
                        .addContainerGap(45, Short.MAX_VALUE))
                    .addComponent(portFormatedField, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelForPort)
                    .addComponent(labelForServerName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addressField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portFormatedField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        UserPane.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("UserPane.border.title"), javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 0, 11), resourceMap.getColor("UserPane.border.titleColor"))); // NOI18N
        UserPane.setName("UserPane"); // NOI18N

        loginLabel.setText(resourceMap.getString("loginLabel.text")); // NOI18N
        loginLabel.setName("loginLabel"); // NOI18N

        userNameField.setText(resourceMap.getString("userNameField.text")); // NOI18N
        userNameField.setEnabled(false);
        userNameField.setName("userNameField"); // NOI18N

        passwordLabel.setText(resourceMap.getString("passwordLabel.text")); // NOI18N
        passwordLabel.setName("passwordLabel"); // NOI18N

        repeatPasswordLabel.setText(resourceMap.getString("repeatPasswordLabel.text")); // NOI18N
        repeatPasswordLabel.setName("repeatPasswordLabel"); // NOI18N

        passFieldOne.setEnabled(false);
        passFieldOne.setName("passFieldOne"); // NOI18N

        passFieldTwo.setEnabled(false);
        passFieldTwo.setName("passFieldTwo"); // NOI18N

        javax.swing.GroupLayout UserPaneLayout = new javax.swing.GroupLayout(UserPane);
        UserPane.setLayout(UserPaneLayout);
        UserPaneLayout.setHorizontalGroup(
            UserPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(UserPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(UserPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(repeatPasswordLabel)
                    .addComponent(passwordLabel)
                    .addComponent(loginLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(UserPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(passFieldOne, javax.swing.GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE)
                    .addComponent(userNameField, javax.swing.GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE)
                    .addComponent(passFieldTwo, javax.swing.GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE))
                .addContainerGap())
        );
        UserPaneLayout.setVerticalGroup(
            UserPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(UserPaneLayout.createSequentialGroup()
                .addGroup(UserPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginLabel)
                    .addComponent(userNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(UserPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordLabel)
                    .addComponent(passFieldOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(UserPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(repeatPasswordLabel)
                    .addComponent(passFieldTwo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        feedBackLabel.setAutoscrolls(true);
        feedBackLabel.setName("feedBackLabel"); // NOI18N

        javax.swing.GroupLayout serverPaneLayout = new javax.swing.GroupLayout(serverPane);
        serverPane.setLayout(serverPaneLayout);
        serverPaneLayout.setHorizontalGroup(
            serverPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, serverPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(serverPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(feedBackLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
                    .addComponent(UserPane, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, serverPaneLayout.createSequentialGroup()
                        .addComponent(updateServerListButton, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeServerFromListButton, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        serverPaneLayout.setVerticalGroup(
            serverPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(serverPaneLayout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(UserPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(serverPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(updateServerListButton)
                    .addComponent(removeServerFromListButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(feedBackLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(serverPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(serverPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(22, 22, 22))
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel UserPane;
    private javax.swing.JTextField addressField;
    private javax.swing.JLabel feedBackLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelForPort;
    private javax.swing.JLabel labelForServerName;
    private javax.swing.JLabel loginLabel;
    private javax.swing.JPasswordField passFieldOne;
    private javax.swing.JPasswordField passFieldTwo;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JTextField portFormatedField;
    private javax.swing.JList reflectorServerList;
    private javax.swing.JButton removeServerFromListButton;
    private javax.swing.JLabel repeatPasswordLabel;
    private javax.swing.JPanel serverPane;
    private javax.swing.JButton updateServerListButton;
    private javax.swing.JTextField userNameField;
    // End of variables declaration//GEN-END:variables
}
